/*
 * @Description: 知悉范围上下文
 * @Author: Rfan
 * @Date: 2022-04-07 15:49:26
 * @LastEditTime: 2022-05-25 09:00:34
 */

import { createContext, useContext, useReducer } from 'react';
import { Modal } from 'antd';
import { ScopeOfKnowledgeReducer } from '../reducers/ScopeOfKnowledgeReducer';
import {
  ADD_SCOPE,
  DELETE_SCOPE,
  SET_SCOPE_LIST,
  SET_SELECTED_ITEM,
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_LEVEL
} from '../constants';
import {
  createScopeOfKonwledge,
  deleteScopeOfKonwledge,
  fetchScopeOfKonwledgeListByPage
} from '@/api/right';

const initialState = {
  // 当前选中的项目
  selectUnit: {},
  selectFond: {},
  selectAT: {},
  selectLevel: {},

  initRule: {},
  // 选中的表格条目
  selectItems: [],
  // 规则列表
  list: [],

  // -------- 字典 --------
  validTypes: [
    { id: 0, name: '有效', color: 'blue' },
    { id: 1, name: '无效', color: 'red' }
  ]
};

const ScopeOfKnowledgeContext = createContext();

const ScopeOfKnowledgeContextProvider = (props) => {
  const [state, dispatch] = useReducer(ScopeOfKnowledgeReducer, initialState);

  const actions = {
    /**
     * @description: 打开新增全宗弹窗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的层级
     */
    setSelectLevel(data) {
      dispatch({ type: SET_SELECT_LEVEL, data });
    },

    getScopeOfKnowledgeList(query) {
      return new Promise((resolve, reject) => {
        fetchScopeOfKonwledgeListByPage(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_SCOPE_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 添加知悉范围
     * @param {*} data 请求参数
     */
    addSOKFunc(data) {
      return new Promise((resolve, reject) => {
        createScopeOfKonwledge(data)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_SCOPE, data });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 删除知悉范围
     * @param {number|number[]} id
     */
    delSOKFunc(id) {
      Modal.confirm({
        title: '删除',
        content: '确认删除该知悉范围？',
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteScopeOfKonwledge(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_SCOPE, ids: data });
            dispatch({ type: SET_SELECTED_ITEM, data: [] });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  const filters = {
    validTypesFilter(id) {
      return state.validTypes.find((type) => type.id === id);
    }
  };

  return (
    <ScopeOfKnowledgeContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </ScopeOfKnowledgeContext.Provider>
  );
};

export const useScopeOfKnowledgeContext = () => {
  return useContext(ScopeOfKnowledgeContext);
};

export { ScopeOfKnowledgeContext, ScopeOfKnowledgeContextProvider };
